package com.gg.cart.controller;

import com.gg.cart.service.CartService;
import com.gg.cart.service.impl.CartServiceImpl;
import com.gg.entity.Cart;
import com.gg.entity.Fruit;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.logging.Logger;

@WebServlet(name = "AddToCartServlet", value = "/cart/AddToCartServlet")
public class AddToCartServlet extends HttpServlet {
    // Servlet 代码
    private static final Logger logger = Logger.getLogger(AddToCartServlet.class.getName());
    private CartService cartService = new CartServiceImpl();

   @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        // 设置响应内容类型为JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 获取并验证参数
        String fruitIdStr = request.getParameter("fruitId");
        String fruitName = request.getParameter("fruitName");
        String fruitNorm = request.getParameter("fruitNorm");
        String fruitPriceStr = request.getParameter("fruitPrice");
        String quantityStr = request.getParameter("quantity");
        String userId = request.getParameter("userId");

        // 验证必需参数
        if (fruitIdStr == null || fruitName == null || fruitNorm == null || 
            fruitPriceStr == null || quantityStr == null || userId == null) {
            response.getWriter().print("{\"success\": false, \"message\": \"缺少必需参数\"}");
            return;
        }

        // 转换参数
        Integer f_id = Integer.parseInt(fruitIdStr);
        BigDecimal f_price = new BigDecimal(fruitPriceStr);
        Integer count = Integer.parseInt(quantityStr);

        // 创建Fruit对象
        Fruit fruit = new Fruit();
        fruit.setF_id(f_id);
        fruit.setF_name(fruitName);
        fruit.setF_norm(fruitNorm);
        fruit.setF_price(f_price);

        // 创建Cart对象
        Cart cart = new Cart();
        cart.setFid(f_id);
        cart.setUid(userId);
        cart.setCcount(count);

        // 调用服务层添加购物车
        boolean res = cartService.addToCart(cart, fruit);

        // 返回结果
        if (res) {
            response.getWriter().print("{\"success\": true, \"message\": \"添加购物车成功\"}");
        } else {
            response.getWriter().print("{\"success\": false, \"message\": \"添加购物车失败\"}");
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
        response.getWriter().print("{\"success\": false, \"message\": \"参数格式错误: " + e.getMessage() + "\"}");
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().print("{\"success\": false, \"message\": \"服务器错误: " + e.getMessage() + "\"}");
    }
}

}
